import React, { useState, useEffect } from 'react';
import { ossApi } from '../../ObjectForImage/utils/ossApi';
import { FileItem, FolderItem } from '../../ObjectForImage/types';
import { getFileIcon, formatFileSize } from '../../ObjectForImage/utils/fileUtils';

interface OSSFileSelectorProps {
  value: string | string[];
  onChange: (value: string | string[]) => void;
  multiple?: boolean;
  placeholder?: string;
}

const OSSFileSelector: React.FC<OSSFileSelectorProps> = ({
  value,
  onChange,
  multiple = false,
  placeholder = "选择文件"
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [currentFolder, setCurrentFolder] = useState('');
  const [folderPath, setFolderPath] = useState<string[]>([]);
  const [folders, setFolders] = useState<FolderItem[]>([]);
  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<Set<string>>(new Set());

  // 初始化选中的文件
  useEffect(() => {
    if (multiple && Array.isArray(value)) {
      setSelectedFiles(new Set(value));
    } else if (!multiple && typeof value === 'string' && value) {
      setSelectedFiles(new Set([value]));
    }
  }, [value, multiple]);

  // 加载文件列表
  const loadFileList = async () => {
    setLoading(true);
    try {
      if (currentFolder === '') {
        const data = await ossApi.getFolders();
        setFolders(data.folders || []);
        setFiles([]);
      } else {
        const data = await ossApi.getFolderContents(currentFolder);
        setFolders(data.subFolders || []);
        setFiles(data.files || []);
      }
    } catch (error) {
      console.error('加载文件列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 导航到文件夹
  const navigateToFolder = (folderName: string) => {
    if (folderName === '') {
      setCurrentFolder('');
      setFolderPath([]);
    } else {
      if (currentFolder === '') {
        setCurrentFolder(folderName);
        setFolderPath([folderName]);
      } else {
        setCurrentFolder(currentFolder + '/' + folderName);
        setFolderPath([...folderPath, folderName]);
      }
    }
  };

  // 处理文件选择
  const handleFileSelect = (fileUrl: string) => {
    if (multiple) {
      const newSelected = new Set(selectedFiles);
      if (newSelected.has(fileUrl)) {
        newSelected.delete(fileUrl);
      } else {
        newSelected.add(fileUrl);
      }
      setSelectedFiles(newSelected);
      onChange(Array.from(newSelected));
    } else {
      setSelectedFiles(new Set([fileUrl]));
      onChange(fileUrl);
      setIsOpen(false);
    }
  };

  // 打开选择器时加载文件
  const handleOpen = () => {
    if (!isOpen) {
      setIsOpen(true);
      loadFileList();
    } else {
      setIsOpen(false);
    }
  };

  // 面包屑导航
  const renderBreadcrumb = () => (
    <div className="flex items-center text-sm text-gray-600 mb-3 border-b pb-2">
      <button
        onClick={() => navigateToFolder('')}
        className="text-blue-600 hover:underline"
      >
        📁 根目录
      </button>
      {folderPath.map((folder, index) => (
        <React.Fragment key={index}>
          <span className="mx-2">/</span>
          <button
            onClick={() => {
              const pathToNavigate = folderPath.slice(0, index + 1).join('/');
              navigateToFolder(pathToNavigate);
            }}
            className="text-blue-600 hover:underline"
          >
            {folder}
          </button>
        </React.Fragment>
      ))}
    </div>
  );

  // 图片预览组件
  const ImagePreview: React.FC<{ file: FileItem }> = ({ file }) => {
    const [imageError, setImageError] = useState(false);

    if (file.type !== 'image' || imageError) {
      return <div className="text-2xl">{getFileIcon(file.type)}</div>;
    }

    return (
      <img
        src={file.customUrl}
        alt={file.fileName}
        className="w-9 h-16 object-content rounded"
        onError={() => setImageError(true)}
      />
    );
  };

  // 获取显示值
  const getDisplayValue = () => {
    if (multiple) {
      const selectedCount = Array.isArray(value) ? value.length : 0;
      return selectedCount > 0 ? `已选择 ${selectedCount} 个文件` : placeholder;
    } else {
      return value || placeholder;
    }
  };

  useEffect(() => {
    if (isOpen) {
      loadFileList();
    }
  }, [currentFolder, isOpen]);

  return (
    <div className="relative">
      {/* 选择器输入框 */}
      <div
        onClick={handleOpen}
        className="w-full px-3 py-2 border border-gray-300 rounded-lg cursor-pointer bg-white hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
      >
        <div className="flex items-center justify-between">
          <span className={`${!value || (Array.isArray(value) && value.length === 0) ? 'text-gray-400' : 'text-gray-900'}`}>
            {getDisplayValue()}
          </span>
          <span className={`transform transition-transform ${isOpen ? 'rotate-180' : ''}`}>
            ▼
          </span>
        </div>
      </div>

      {/* 下拉面板 */}
      {isOpen && (
        <div className="absolute top-full left-0 right-0 z-50 mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-96 overflow-hidden">
          <div className="p-3">
            {renderBreadcrumb()}
            
            {loading ? (
              <div className="text-center py-4">
                <div className="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
                <div className="mt-2 text-gray-600">加载中...</div>
              </div>
            ) : (
              <div className="max-h-64 overflow-y-auto">
                {/* 文件夹列表 */}
                {folders.map((folder) => (
                  <div
                    key={folder.name}
                    onClick={() => navigateToFolder(folder.name)}
                    className="flex items-center p-2 hover:bg-gray-100 cursor-pointer rounded"
                  >
                    <span className="text-xl mr-3">📁</span>
                    <span className="text-sm font-medium">{folder.displayName}</span>
                  </div>
                ))}

                {/* 文件列表 */}
                {files.map((file) => (
                  <div
                    key={file.name}
                    onClick={() => handleFileSelect(file.customUrl)}
                    className={`flex items-center p-2 hover:bg-gray-100 cursor-pointer rounded ${
                      selectedFiles.has(file.customUrl) ? 'bg-blue-50 border border-blue-200' : ''
                    }`}
                  >
                    <div className="mr-3 flex-shrink-0">
                      <ImagePreview file={file} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium truncate">{file.fileName}</div>
                      <div className="text-xs text-gray-500">
                        {file.type} • {formatFileSize(file.size)}
                      </div>
                    </div>
                    {multiple && selectedFiles.has(file.customUrl) && (
                      <div className="ml-2 text-blue-600">✓</div>
                    )}
                  </div>
                ))}

                {folders.length === 0 && files.length === 0 && (
                  <div className="text-center py-4 text-gray-500">
                    📂 文件夹为空
                  </div>
                )}
              </div>
            )}
          </div>

          {/* 多选模式的确认按钮 */}
          {multiple && (
            <div className="border-t p-3 bg-gray-50">
              <button
                onClick={() => setIsOpen(false)}
                className="w-full px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
              >
                确认选择 ({selectedFiles.size} 个文件)
              </button>
            </div>
          )}
        </div>
      )}

      {/* 遮罩层 */}
      {isOpen && (
        <div
          className="fixed inset-0 z-40"
          onClick={() => setIsOpen(false)}
        />
      )}
    </div>
  );
};

export default OSSFileSelector; 